package com.aaa.demo08;

/**
 * @author ${崔灿}
 * @date 2022/11/01 16:37
 **/

public class BankCard {
    private double balance;
    //表示有钱没钱：true表示有钱 false 表示没钱
    private boolean flag;

    // 存钱方法 synchronized 在方法上加synchronized 表示整个方法都上锁 默认的锁对象就是this对象
     public synchronized void save(double money) {
         System.out.println(Thread.currentThread().getName());

         //卡中有钱--无需存钱
         if (flag==true) {
             try {
                 wait();
             }catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         balance=balance+money;
         System.out.println(Thread.currentThread().getName()+"存入了"+money+"元，卡中余额："+balance);
        flag = true;
        //唤醒等待队列中的线程
         notify();
     }

     public synchronized void token(double money){
         System.out.println(Thread.currentThread().getName());
         if (flag == false) {
             try {
                 wait();
             }catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }

         balance= balance-money;
         System.out.println(Thread.currentThread().getName()+"取出了"+money + "元，卡中余额："+balance);
         flag= false;
         notify();
     }
}
